<template>
  <el-container>
    <el-main>
      <div v-if="loading" class="loading">加载中...</div>
      
      <div v-else-if="posts && posts.length">
        <el-card v-for="post in posts" :key="post.ID" class="post-card">
          <h2>{{ post.title }}</h2>
          <p><strong>话题:</strong> {{ post.topic }}</p>
          <p>{{ post.content.length > 100 ? post.content.substring(0, 100) + '...' : post.content }}</p>
          <p><strong>发布时间:</strong> {{ new Date(post.CreatedAt).toLocaleString() }}</p>
          <el-button text @click="viewDetail(post.ID)">阅读更多</el-button>
        </el-card>
      </div>
      
      <div v-else class="no-data">暂无帖子</div>
      
      <!-- 分页组件 -->
      <el-pagination
        v-if="posts.length > 0"
        class="pagination"
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from '../axios';
import { useAuthStore } from '../store/auth';
import type { Post } from "../types/Article";

const posts = ref<Post[]>([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(7);
const totalPages = ref(1);
const router = useRouter();
const authStore = useAuthStore();

const fetchPosts = async (page = 1) => {
  loading.value = true;
  currentPage.value = page;
  
  try {
    const response = await axios.get('/api/posts', {
      params: {
        page: page,
        size: pageSize.value
      }
    });
    console.log('API响应数据:', response.data); // 调试用
    
    // 处理带分页的数据结构
    if (response.data && response.data.posts) {
      posts.value = response.data.posts;
      total.value = response.data.total || 0;
      totalPages.value = response.data.totalPages || 1;
      pageSize.value = response.data.size || 7;
    } else if (Array.isArray(response.data)) {
      // 直接是数组的情况（不太可能出现，但以防万一）
      posts.value = response.data;
      total.value = response.data.length;
    } else {
      console.warn('未知的响应格式:', response.data);
      posts.value = [];
    }
  } catch (error) {
    console.error('加载帖子失败:', error);
    posts.value = [];
  } finally {
    loading.value = false;
  }
};

// 切换页面
 const handlePageChange = (page: number) => {
  fetchPosts(page);
 };

const viewDetail = (id: number) => {
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录后再查看');
    return;
  }
  //一定注意到路由的使用，这里的路由是通过name来跳转的，所以需要在路由中定义好name为NewsDetail的页面
  router.push({ name: 'NewsDetail', params: { id } });
};

onMounted(fetchPosts);
</script>

<style scoped>
.post-card {
  margin: 20px 0;
}

.no-data {
  text-align: center;
  font-size: 16px;
  color: #999;
  margin-top: 20px;
}

.loading {
  text-align: center;
  font-size: 16px;
  color: #409EFF;
  margin: 30px 0;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style>
